<template>
  <div class="add-role">
    <el-form label-width="80px">
      <el-form-item label="角色名称">
        <el-input v-model="form.rolename"></el-input>
      </el-form-item>
      <el-form-item label="角色权限">
        <el-tree
          ref="treeRef"
          :data="menuList"
          show-checkbox
          node-key="id"
          default-expand-all
          :props="{ label: 'title' }"
        >
        </el-tree>
      </el-form-item>
      <el-form-item label="状态">
        <el-switch
          v-model="form.status"
          :active-value="1"
          :inactive-value="2"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="commit">修改</el-button>
        <el-button @click="$router.push('/role')" type="info">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getListApi } from '@/api/admin'
import { setRoleApi, getRoleApi } from '@/api/roles'
export default {
  data() {
    return {
      menuList: [],
      form: {
        rolename: "",
        status: 1,
      },
    };
  },
  mounted() {
    this.getMenuList();
    this.getOne()
  },
  methods: {
    async getMenuList() {
      let res = await getListApi(true);
      this.menuList = res.list;
      /* console.log(res); */
    },
    async commit() {
      let res = this.$refs.treeRef.getCheckedKeys();
      this.form.menus = res;
      /* console.log(this.form); */
      this.form.id=this.$route.query.id
      let data = await setRoleApi(this.form);
      if (data.code == 200) {
        alert(data.msg);
        this.form.rolename = "";
        this.form.status = 1;
      } else {
        alert(data.msg);
      }
    },
    //获取初始化数据
    async getOne(){
        let res=await getRoleApi(this.$route.query.id)
        this.form=res.list
        let arr=res.list.menus.split(',')
        console.log(arr);
        this.$nextTick(() => {
          arr.forEach((item) => {
            this.$refs.treeRef.setChecked(item, true)
          })
        })
    }
  },
};
</script>
<style>
</style>
